package MST;

import java.util.*;

/**
 * @Author: Siantar
 * @Date: 2023-06-22-21:44
 * @Description: 1.0
 */
public class MST1619 {
    int[][] dirs = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};

    public int[] pondSizes(int[][] land) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < land.length; i++) {
            for (int j = 0; j < land[0].length; j++) {
                if (land[i][j] == 0) {
                    list.add(dfs(land, i, j));
                }
            }
        }
        return list.stream().sorted().mapToInt(Integer::intValue).toArray();
    }

    public int dfs(int[][] land, int x, int y) {
        Queue<int[]> queue = new ArrayDeque<>();
        queue.offer(new int[]{x, y});
        land[x][y] = 1;
        int res = 1;
        while (!queue.isEmpty()) {
            int[] t = queue.poll();
            for (int i = 0; i < 8; i++) {
                int tx = t[0] + dirs[i][0], ty = t[1] + dirs[i][1];
                if (tx >= 0 && tx < land.length && ty >= 0 && ty < land[0].length && land[tx][ty] == 0) {
                    queue.offer(new int[]{tx, ty});
                    land[tx][ty] = 1;
                    res++;
                }
            }
        }
        return res;
    }
}
